/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package collection;

import dto.Image;
import dto.Product;
import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author duonghung1369
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "products")
public class Products implements Serializable {

    @XmlElement(name = "product", required = true)
    private List<Product> products;
    @XmlTransient
    private boolean found;

    public Products() {
        found = false;
    }

    public Products(List<Product> products) {
        this.products = products;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    public Product contains(int productId) {
        if (this.getProducts() != null) {
            for (Product p : products) {
                if (p.getId() == productId) {
                    return p;
                }
            }
        }

        return null;
    }

    /**
     * Filter product for display products in homepage.
     * If categoryId != -1, then just filter showed = true and deleted = false
     * else so filter by category, then filter showed = true, deleted = false, product.getCategory.id = categoryId
     * @param categoryId
     */
    public void filterDisplayHomepage(int categoryId) {
        if (this.getProducts() != null) {
            Product tmp;
            for (int i = 0; i < products.size(); i++) {
                tmp = products.get(i);

                if (categoryId != -1) { // filter by category
                    if (tmp.getCategory().getId() != categoryId) { // remove product that not belong to categoryId
                        products.remove(tmp);
                        i--;
                    } else { // if product belong to category, check if it's deleted
                        if (tmp.isIsDeleted()) {
                            products.remove(tmp);
                            i--;
                        }
                    }
                } else { // just filter by deleted and isShowed
                    if (tmp.isIsDeleted() || !tmp.isIsShowed()) {
                        products.remove(tmp);
                        i--;
                    }
                }

            }
        }
    }

    public void addProductNode(Document doc, Product product) {
        String imageNS = "http://xml.netbeans.org/schema/image";
        String prefixImage = "ns2:";

        Element productElement = doc.createElement("product");
        productElement.setAttribute("id", product.getId() + "");

        Element nameElement = doc.createElement("name");
        nameElement.setTextContent(product.getName());
        //Append nameElement to productElement
        productElement.appendChild(nameElement);

        Element categoryElement = doc.createElement("category");
        Element categoryName = doc.createElement("name");
        categoryName.setTextContent(product.getCategory().getName());
        Element categoryDeleted = doc.createElement("deleted");
        categoryDeleted.setTextContent(product.getCategory().isIsDeleted() + "");
        categoryElement.appendChild(categoryName);
        categoryElement.appendChild(categoryDeleted);
        //Append categoryElement to productElement
        productElement.appendChild(categoryElement);



        Element descriptionElement = doc.createElement("description");
        descriptionElement.setTextContent(product.getDescription());
        //Append descriptionElement to productElement
        productElement.appendChild(descriptionElement);

        Element priceElement = doc.createElement("price");
        priceElement.setTextContent(product.getPrice() + "");
        //Append priceElement to productElement
        productElement.appendChild(priceElement);

        Element quantityElement = doc.createElement("quantity");
        quantityElement.setTextContent(product.getQuantity() + "");
        //Append quantityElement to productElement
        productElement.appendChild(quantityElement);


        Element createdDateElement = doc.createElement("createdate");
        if (product.getCreateDate() != null) {
            createdDateElement.setTextContent(product.getCreateDate().toString());
        }
        //Append createdDateElement to productElement
        productElement.appendChild(createdDateElement);

        Element updatedateElement = doc.createElement("updatedate");
        if (product.getUpdateDate() != null) {
            updatedateElement.setTextContent(product.getUpdateDate().toString());
        }
        //Append updateddateElement to productElement
        productElement.appendChild(updatedateElement);

        Element isdeletedElement = doc.createElement("isdeleted");
        isdeletedElement.setTextContent(product.isIsDeleted() + "");
        //Append isdeletedElement to productElement
        productElement.appendChild(isdeletedElement);

        Element isshowedElement = doc.createElement("isshowed");
        isshowedElement.setTextContent(product.isIsShowed() + "");
        //Append isshoedElement to productElement
        productElement.appendChild(isshowedElement);

        Element imagesElement = doc.createElement("images");
        Element imageElement;
        List<Image> imageList = product.getImages();
        if (!imageList.isEmpty()) {
            for (Image image : imageList) {
                imageElement = doc.createElement("image");
                imageElement.setAttribute(prefixImage + "id", image.getId() + "");

                Element nameImage = doc.createElement(prefixImage + "name");
                nameImage.setTextContent(image.getName());

                Element descriptionImage = doc.createElement(prefixImage + "description");
                descriptionImage.setTextContent(image.getDescription());

                Element urlImage = doc.createElement(prefixImage + "url");
                urlImage.setTextContent(image.getUrl());

                //Append url, name, description to image elemt
                imageElement.appendChild(nameImage);
                imageElement.appendChild(descriptionImage);
                imageElement.appendChild(urlImage);

                //Append imageElement to imagesElement
                imagesElement.appendChild(imageElement);
            }
        }//End imagesElement
        //Append imagesElement to productElement   
        if (imagesElement != null) {
            productElement.appendChild(imagesElement);
        }

        //Append new node to doc
        NodeList products = doc.getElementsByTagName("products");
        products.item(0).appendChild(productElement);
    }

    public void deleteProductNode(Node node, String productId) {
        if (node == null || found) {
            return;
        }

        if (node.getNodeName().equals("product")) {
            //Get attributeId
            String attributeId = node.getAttributes().getNamedItem("id").getNodeValue();
            if (productId.equals(attributeId)) {
                //Found product and set isDelete
                NodeList childList = node.getChildNodes();
                Node temp;
                for (int i = 0; i < childList.getLength(); i++) {
                    temp = childList.item(i);
                    if ("isdeleted".equals(temp.getNodeName())) {
                        if ("true".equals(temp.getTextContent())) {
                            temp.setTextContent("false");
                        } else if ("false".equals(temp.getTextContent())) {
                            temp.setTextContent("true");
                        }
                        found = true;
                        return;
                    }
                }
            }
        }
        int i = 0;
        NodeList child = node.getChildNodes();
        while(i <child.getLength()) {
            deleteProductNode(child.item(i++), productId);
        }
    }

    public Product getProductById(int id) {
        Product result = null;


        boolean notFound = true;


        for (int i = 0; notFound
                && i < products.size(); i++) {
            if (products.get(i).getId() == id) {
                result = products.get(i);
                notFound = false;


            }
        }
        return result;

    }
}
